import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null;
    }
}

class Solution {
    //解法1：迭代 + 拼接 + 拆分
    public Node copyRandomList(Node head) {
        if (head == null) return null;
        Node curNode = head;
        //原链表每个节点后面拼接一个相同的节点
        while (curNode != null) {
            Node node = new Node(curNode.val);
            node.next = curNode.next;
            curNode.next = node;
            curNode = node.next;
        }
        //为新拼接节点的random域赋值
        curNode = head;
        while (curNode != null) {
            if (curNode.random != null) {
                curNode.next.random = curNode.random.next;
            }
            curNode = curNode.next.next;
        }
        //拆分新旧链表
        Node preNode = head;
        curNode = head.next;
        Node newHead = head.next;
        while (curNode.next != null) {
            preNode.next = preNode.next.next;
            curNode.next = curNode.next.next;
            preNode = preNode.next;
            curNode = curNode.next;
        }
        preNode.next = null;
        return newHead;
    }
    //解法2：哈希表+回溯
}